package com.redistest.seckill.service;

import com.redistest.seckill.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    // 存储Token到Redis
    public void storeToken(String username, String token) {
        redisTemplate.opsForValue().set(
                "token:" + username,
                token,
                jwtTokenUtil.getExpiration(token),
                TimeUnit.SECONDS
        );
    }

    // 从Redis获取Token
    public String getToken(String username) {
        return redisTemplate.opsForValue().get("token:" + username);
    }

    // 删除Token
    public void deleteToken(String username) {
        redisTemplate.delete("token:" + username);
    }

    // 验证Token是否存在
    public boolean validateToken(String username, String token) {
        String storedToken = getToken(username);
        return storedToken != null && storedToken.equals(token);
    }
}
